" show the quickfix window
nnoremap <silent> <leader>co :copen<CR>
nnoremap <silent> <leader>cl :lopen<CR>

" hide the quickfix window
nnoremap <silent> <leader>cc :cclose<CR>

function! QuicklistMove(qcommand, qcommand_fallback) abort
  let l:winid = winnr()
  let l:qcommand = a:qcommand
  let l:qcommand_fallback = a:qcommand_fallback
  if execute("file") =~# "Location List"
    let l:qcommand = 'l' . a:qcommand[1:]
    let l:qcommand_fallback = 'l' . a:qcommand_fallback[1:]
  endif
  try
    execute l:qcommand
  catch /^Vim\%((\a\+)\)\=:E553:/
    execute l:qcommand_fallback
  catch /^Vim\%((\a\+)\)\=:E42:/
    echohl ErrorMsg | echo "Vim E42, No item here" | echohl None
  endtry
  execute 'normal zz'
  execute l:winid . "wincmd w"
endfunction

function! QuickfixMapping()
  " hide the quickfix window
  nnoremap <buffer> q <Cmd>close<CR>

  " go to the previous location and stay in the quickfix window
  nnoremap <silent><buffer> K :call QuicklistMove('cprev', 'clast')<CR>

  " go to the next location and stay in the quickfix window
  nnoremap <silent><buffer> J :call QuicklistMove('cnext', 'cfirst')<CR>

  nnoremap <buffer> <BS> <CR><C-w><C-p>

  " begin the search and replace
  nnoremap <buffer> <leader>r :cdo s/// \| update<C-Left><C-Left><Left><Left><Left>
endfunction

augroup Quickfix_setting
    autocmd!
    autocmd filetype qf call QuickfixMapping()
augroup END

" Quickfix list mappings
nnoremap [q :<C-u>exe 'cprevious' v:count1<CR>
nnoremap ]q :<C-u>exe 'cnext' v:count1<CR>
nnoremap [Q :<C-u>exe 'crewind' (v:count != 0 ? v:count : '')<CR>
nnoremap ]Q :<C-u>exe 'clast' (v:count != 0 ? v:count : '')<CR>
nnoremap [<C-Q> :<C-u>exe 'cpfile' v:count1<CR>
nnoremap ]<C-Q> :<C-u>exe 'cnfile' v:count1<CR>

" Location list mappings
nnoremap [l :<C-u>exe 'lprevious' v:count1<CR>
nnoremap ]l :<C-u>exe 'lnext' v:count1<CR>
nnoremap [L :<C-u>exe 'lrewind' (v:count != 0 ? v:count : '')<CR>
nnoremap ]L :<C-u>exe 'llast' (v:count != 0 ? v:count : '')<CR>
nnoremap [<C-L> :<C-u>exe 'lpfile' v:count1<CR>
nnoremap ]<C-L> :<C-u>exe 'lnfile' v:count1<CR>
